<?php

namespace app\admin\service;

use   app\admin\controller\Dbfimport;
use think\Db;

class OllamaService
{




    function automaticindexing($id)
    {


        $Dbfimport = new Dbfimport();

        $jsonData = $Dbfimport->getUniqueString($id, 3);


        $json = file_get_contents($jsonData);

        $list = json_decode($json, true);


        $text = json_encode($list[0]['sorest'], JSON_UNESCAPED_UNICODE);


        $data = $list[0]['sorest'][0];

        $text = $this->automaticLineWrapping($data);


        $num = count($list);


        if ($num > 1) {
            $endData = $list[$num - 1]['sorest'][0];
            $endText = $this->automaticLineWrapping($endData);
            $text = $text . "\n\n\n\n\n\n" . $endText;
        }


        $question = "这是百度飞桨ocr提取内容：'{$text}' 现在您帮我提取出   时间用sj字段时间格式用yyyy-mm-dd格式、主题词用ztc字段、密级用mj字段、关键词用gjc字段、类别号用lbh字段、文种用wz字段、标题用tm字段,文件编号用wjbh字段、责任者用zrz字段、微缩号用swh字段、档案馆代号用dagdh字段。假设你是自动标引智能机器人 请根据提供的信息生成一个JSON对象。注意：只返回JSON内容，不需要包括任何额外的标记或说明 你不要返回我```json标记。 字段的值肯定是字符串";

        $ollamaURL = config("ollamaURL");


        $ch = curl_init();


        curl_setopt($ch, CURLOPT_URL, $ollamaURL . '/api/chat');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);

        $headers = [
            'Authorization: Bearer sk-tiuvcznrtvpmjnipckrwiaotbspbpeslgbxadpwznrfdqocc',
            'Content-Type: application/json'
        ];
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        $data = [
            "model" => "qwen2.5:7b",
            "messages" => [
                [
                    "role" => "user",
                    "content" => $question
                ]
            ],
            "stream" => false,
            "max_tokens" => 512,
            "stop" => ["<string>"],
            "temperature" => 0.7,
            "top_p" => 0.7,
            "top_k" => 50,
            "frequency_penalty" => 0.5,
            "n" => 1,
            "response_format" => ["type" => "json_object"]
        ];

        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));

        $result = curl_exec($ch);
        if (curl_errno($ch)) {
            echo 'Error:' . curl_error($ch);
        }
        curl_close($ch);

// 解析返回结果
        $response = json_decode($result, true);


        return $response;


    }

    function autoxiaozhun($id)
    {


        $textData = Db::table("zstp_article")->where(array("id" => $id))->field("content")->find();

        $ollamaURL = config("ollamaURL");


        $question = "以下是一个图片OCR识别结果，请将其中可能出现的错误文字、错误分段或换行校正，注意尽量忠于原文，以JSON格式返回校正结果,不要返回我```JSON返回我JSON对象，其中correction_results字段为校正后的最终内容,summary字段为做了哪些校对的小结。需要校对的原始内容如下：" . $textData['content'];

        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $ollamaURL . '/api/chat');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);

        $headers = [
            'Authorization: Bearer sk-tiuvcznrtvpmjnipckrwiaotbspbpeslgbxadpwznrfdqocc',
            'Content-Type: application/json'
        ];
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        $data = [
            "model" => "qwen2.5:7b",
            "messages" => [
                [
                    "role" => "user",
                    "content" => $question
                ]
            ],
            "stream" => false,
            "max_tokens" => 512,
            "stop" => [" < string>"],
            "temperature" => 0.7,
            "top_p" => 0.7,
            "top_k" => 50,
            "frequency_penalty" => 0.5,
            "n" => 1,
            "response_format" => ["type" => "json_object"]
        ];

        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));

        $result = curl_exec($ch);
        if (curl_errno($ch)) {
            echo 'Error:' . curl_error($ch);
        }
        curl_close($ch);

// 解析返回结果
        $response = json_decode($result, true);


        return $response;


    }


    function automaticLineWrapping($data)
    {

        // 按照 y 值分组
        $lines = [];
        foreach ($data as $item) {
            $coords = $item[0];
            $text = $item[1][0];
            $y = ($coords[0][1] + $coords[2][1]) / 2; // 取矩形上下边界的平均值作为 y 坐标

            $added = false;
            foreach ($lines as &$line) {
                if ($this->isSameLine($y, $line['y'])) {
                    $line['texts'][] = $text;
                    $added = true;
                    break;
                }
            }
            if (!$added) {
                $lines[] = ['y' => $y, 'texts' => [$text]];
            }
        }

// 输出结果
        $result = '';
        foreach ($lines as $line) {
            $result .= implode(' ', $line['texts']) . "\n"; // 同一行的文本用空格连接
        }

        return $result;


    }

    // 定义一个函数，用于计算两行 y 值是否接近
    function isSameLine($y1, $y2, $tolerance = 10)
    {
        return abs($y1 - $y2) <= $tolerance;
    }


}